<template>
  <view class="page">
    <view class="content">
      <!-- 订单基本信息 -->
      <view class="order-info">
        <view class="order-no">订单号：{{ order.order_no }}</view>
        <view class="order-time">{{ formatTime(order.create_date) }}</view>
      </view>

      <!-- 总体评分区域 -->
      <view class="rating-card">
        <view class="section-title">订单总体评分 <text class="required">*</text></view>
        
        <!-- 星级评分 -->
        <view class="star-rating">
          <view 
            v-for="star in 5" 
            :key="star"
            class="star"
            :class="{ active: star <= overallScore }"
            @click="setOverallScore(star)"
          >
            ★
          </view>
        </view>
        
        <view class="score-display">{{ overallScore }} 分</view>
        
        <!-- 总体评价 -->
        <view class="comment-section">
          <view class="label">总体评价（可选）</view>
          <textarea 
            v-model="overallComment"
            class="textarea"
            placeholder="请输入您的评价..."
            maxlength="500"
            :auto-height="true"
          />
          <view class="char-count">{{ overallComment.length }}/500</view>
        </view>
      </view>

      <!-- 菜品评分区域 -->
      <view class="dishes-rating-card">
        <view class="section-title">菜品评分（可选）</view>
        
        <view 
          v-for="(dish, index) in order.dishes" 
          :key="index"
          class="dish-rating-item"
        >
          <view class="dish-header">
            <view class="dish-name">{{ dish.name }}</view>
            <view class="dish-qty">×{{ dish.count }}</view>
          </view>
          
          <!-- 菜品星级评分 -->
          <view class="star-rating">
            <view 
              v-for="star in 5" 
              :key="star"
              class="star"
              :class="{ active: star <= (dishRatings[index]?.score || 0) }"
              @click="setDishScore(index, star)"
            >
              ★
            </view>
          </view>
          
          <!-- 菜品评价 -->
          <textarea 
            v-model="dishRatings[index].comment"
            class="textarea"
            placeholder="对这道菜的看法..."
            maxlength="200"
            :auto-height="true"
          />
          <view class="char-count">{{ dishRatings[index].comment.length }}/200</view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="actions">
        <button class="btn-cancel" @click="goBack">取消</button>
        <button class="btn-submit" :disabled="overallScore === 0" @click="submitRating">
          提交评价
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const order = ref({
  _id: '',
  order_no: '',
  create_date: '',
  dishes: []
})
const overallScore = ref(0)
const overallComment = ref('')
const dishRatings = ref([])

// 从路由参数获取订单ID并加载
onLoad((options) => {
  const orderId = options?.orderId
  
  if (!orderId) {
    uni.showToast({
      title: '缺少订单ID',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
    return
  }
  
  loadOrderDetail(orderId)
})

// 加载订单详情
const loadOrderDetail = async (orderId) => {
  try {
    
    const res = await uniCloud.callFunction({
      name: 'food-order',
      data: {
        action: 'get-order-detail',
        data: { order_id: orderId }  // 使用 order_id 而不是 orderId
      }
    })

    
    if (res.result && res.result.code === 200) {
      let orderData = res.result.data || {}
      
      // 处理数据格式 - 如果是数组，取第一个元素
      if (Array.isArray(orderData)) {
        orderData = orderData[0] || {}
      }
      
      order.value = orderData
      
      console.log('=== 加载的订单详情 ===')
      console.log('订单号:', order.value.order_no)
      console.log('订单ID:', order.value._id)
      console.log('菜品数:', order.value.dishes?.length)

      // 初始化菜品评分数据
      dishRatings.value = order.value.dishes.map(dish => ({
        dish_id: dish.id || dish._id,
        dish_name: dish.name,
        score: 0,
        comment: ''
      }))

      // 如果已有评价，加载现有数据
      if (order.value.rating?.rated) {
        overallScore.value = order.value.rating.overall_score || 0
        overallComment.value = order.value.rating.overall_comment || ''
        
        if (order.value.rating.dishes && Array.isArray(order.value.rating.dishes)) {
          order.value.rating.dishes.forEach((dishRating, index) => {
            if (dishRatings.value[index]) {
              dishRatings.value[index].score = dishRating.score || 0
              dishRatings.value[index].comment = dishRating.comment || ''
            }
          })
        }
      }
    } else {
      uni.showToast({
        title: res.result?.message || '加载订单失败',
        icon: 'none'
      })
      setTimeout(() => uni.navigateBack(), 1500)
    }
  } catch (err) {
    uni.showToast({
      title: '加载订单失败',
      icon: 'none'
    })
    setTimeout(() => uni.navigateBack(), 1500)
  }
}

// 设置总体评分
const setOverallScore = (score) => {
  overallScore.value = score
}

// 设置菜品评分
const setDishScore = (index, score) => {
  dishRatings.value[index].score = score
}

// 提交评价
const submitRating = async () => {
  if (overallScore.value === 0) {
    uni.showToast({
      title: '请给订单评分',
      icon: 'none'
    })
    return
  }

  // 构建评价数据
  const ratingData = {
    overall_score: overallScore.value,
    overall_comment: overallComment.value.trim() || null,  // 去空格后，空字符串变为 null
    dishes: dishRatings.value
      .filter(d => d.score > 0)  // 只提交有评分的菜品
      .map(d => ({
        dish_id: d.dish_id,
        dish_name: d.dish_name,
        score: d.score,
        comment: d.comment.trim() || null  // 去空格后，空字符串变为 null
      }))
  }

  try {
    uni.showLoading({ title: '提交中...' })
    
    const res = await uniCloud.callFunction({
      name: 'food-order',
      data: {
        action: 'submit-rating',
        data: {
          orderId: order.value._id,
          rating: ratingData
        }
      }
    })

    uni.hideLoading()

    if (res.result && res.result.code === 200) {
      uni.showToast({
        title: '评价提交成功',
        icon: 'success'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: res.result?.message || '提交失败',
        icon: 'none'
      })
    }
  } catch (err) {
    uni.hideLoading()
    uni.showToast({
      title: '提交评价失败',
      icon: 'none'
    })
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f8fafc;
}

.content {
  padding: 32rpx;
  padding-bottom: 100rpx;
}

/* 订单信息 */
.order-info {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.order-no {
  font-size: 28rpx;
  color: #374151;
  font-weight: 600;
  margin-bottom: 12rpx;
}

.order-time {
  font-size: 24rpx;
  color: #9CA3AF;
}

/* 卡片样式 */
.rating-card,
.dishes-rating-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.section-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #374151;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.required {
  color: #ef4444;
  font-size: 28rpx;
}

/* 星级评分 */
.star-rating {
  display: flex;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.star {
  font-size: 48rpx;
  color: #e5e7eb;
  cursor: pointer;
  transition: color 0.2s ease;

  &.active {
    color: #fbbf24;
  }

  &:active {
    transform: scale(1.1);
  }
}

.score-display {
  font-size: 28rpx;
  color: #6B7280;
  margin-bottom: 24rpx;
}

/* 评论区域 */
.comment-section {
  margin-top: 24rpx;
}

.label {
  font-size: 26rpx;
  color: #374151;
  margin-bottom: 12rpx;
  font-weight: 500;
}

.textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 16rpx;
  border: 1rpx solid #e5e7eb;
  border-radius: 12rpx;
  font-size: 26rpx;
  color: #374151;
  background: #ffffff;
  font-family: inherit;
  resize: none;
}

.char-count {
  font-size: 24rpx;
  color: #9CA3AF;
  margin-top: 8rpx;
  text-align: right;
}

/* 菜品评分项 */
.dish-rating-item {
  background: #f9fafb;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  border: 1rpx solid #e5e7eb;
}

.dish-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.dish-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #374151;
}

.dish-qty {
  font-size: 24rpx;
  color: #9CA3AF;
}

/* 操作按钮 */
.actions {
  display: flex;
  gap: 16rpx;
  padding: 32rpx 0;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  background: #ffffff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.btn-cancel,
.btn-submit {
  flex: 1;
  height: 88rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 600;
  border: none;
}

.btn-cancel {
  background: #ffffff;
  color: #374151;
  border: 1rpx solid #d1d5db;
}

.btn-submit {
  background: #007AFF;
  color: #ffffff;

  &:disabled {
    background: #d1d5db;
    color: #9ca3af;
  }
}
</style>

